package com.rr.sc.bo.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.rr.sc.bo.TransactionBo;
import com.rr.sc.dao.TransactionDao;
import com.rr.sc.model.Transaction;
import com.rr.sc.model.enums.TransactionType;
import com.rr.sc.utils.BoImplUtils;

@Service
public class TransactionBoImpl implements TransactionBo {

	private static transient Logger log = Logger
			.getLogger(TransactionBoImpl.class);

	private TransactionDao transactionDao;

	@Autowired
	private TransactionBoImpl(TransactionDao transactionDao) {
		super();
		this.transactionDao = transactionDao;
	}

	public void saveOrUpdate(Transaction transaction) {
		if (transaction != null) {

			List<Transaction> doubledTransactions = transactionDao
					.searchDoubledTransaction(transaction);

			if (CollectionUtils.isEmpty(doubledTransactions)) {

				if (transaction.getValue() != null
						&& transaction.getValue() > 0) {
					transaction.setType(TransactionType.INCOME);
				} else {
					transaction.setType(TransactionType.EXPENSE);
				}
				if (transaction.getParentTransaction() != null
						&& transaction.getParentTransaction().getId() == null) {
					transaction.setParentTransaction(null);
				}
				transactionDao.saveOrUpdate(transaction);
			}
		}
	}

	public Transaction get(Long id) {
		return transactionDao.get(id);
	}

	public void delete(Transaction transaction) {
		transactionDao.delete(transaction);
	}

	public List<Transaction> getFiltered(Long userId, int month, int year,
			TransactionType transactionType, Long categoryId, Long accountId,
			String currencyId) {
		return transactionDao.getFiltered(BoImplUtils.getAsList(userId), month,
				year, transactionType, categoryId, accountId, currencyId);
	}
}
